package com.c.ctgproject.ui.newvehicles

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.text.Editable
import android.text.InputFilter
import android.text.InputFilter.LengthFilter
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.MenuItem
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.c.ctgproject.R
import com.c.ctgproject.customview.GlideImageLoader
import com.c.ctgproject.customview.ImagePickerLoader
import com.c.ctgproject.retrofit.Response
import com.c.ctgproject.utils.*
import com.c.ctgproject.utils.pickerimage.utils.StorageType
import com.c.ctgproject.utils.pickerimage.utils.StorageUtil
import com.c.ctgproject.utils.pickerimage.utils.StringUtil
import com.jaeger.library.StatusBarUtil
import com.lwkandroid.imagepicker.ImagePicker
import com.lwkandroid.imagepicker.data.ImageBean
import com.lwkandroid.imagepicker.data.ImagePickType
import com.lwkandroid.widget.ninegridview.NineGirdImageContainer
import com.lwkandroid.widget.ninegridview.NineGridBean
import com.lwkandroid.widget.ninegridview.NineGridView
import com.nanchen.compresshelper.CompressHelper
import kotlinx.android.synthetic.main.activity_newvehicles.*
import kotlinx.android.synthetic.main.title.*
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

/**
 * 新建车辆 页面 (档案部)
 */
@Suppress(
    "DEPRECATED_IDENTITY_EQUALS", "DEPRECATION",
    "NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS"
)
class Newvehicles : AppCompatActivity(), View.OnClickListener,  NineGridView.onItemClickListener {
    private val statusColor: StatusColor = StatusColor()
    private val REQUEST_CODE_PICKER = 100
    private var progressDialog: ProgressDialog? = null
    private var dialogUtils: DialogUtils? = null
    private var newvehiclesViewModel: NewvehiclesViewModel? = null
    private var carPlate: String? = null //车牌号
//    private var keyboardUtil: CarKeyboardUtil? = null
    private var drivingLicense = "0"//行驶证 1-有 0-无
    private var registration = "0" //登记证 1-有 0-无
    private var idCardCopy = "0"  //身份证复印件 1-有 0-无
    private var notice = "0" //告知书 1-有 0-无
    private var attorneyPaper = "0" //委托书 1-有 0-无
    private var guaranteed = "0" //是否保号 1-保 0-不保号
    private var operating = "0"//是否营运车辆 1-营运 0-非营运
    private var plateApplicationForm = "0" //机动车申领表 1-有 0-无
    private var carSign = "2"  //车辆标记 1-问题车辆 2-正常车辆
    private var token: String? = null
    private val JPG = ".jpg"
    private val files: ArrayList<File> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_newvehicles)
        StatusBarUtil.setTranslucent(this)
        statusColor.setAndroidNativeLightStatusBar(this, false)
        toolbar_title.text = "新建车辆"
        setSupportActionBar(toolbar)
        supportActionBar?.setHomeButtonEnabled(true)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowTitleEnabled(false)
        event()
        Getdata()
    }

    private fun event() {
        //设置图片加载器，这个是必须的，不然图片无法显示
        ninegridview.setImageLoader(GlideImageLoader())
        //设置显示列数，默认3列
        ninegridview.setColumnCount(3)
        //设置是否为编辑模式，默认为false
        ninegridview.setIsEditMode(true)
        //设置单张图片显示时的尺寸，默认100dp
        ninegridview.setSingleImageSize(150)
        //设置单张图片显示时的宽高比，默认1.0f
        ninegridview.setSingleImageRatio(0.8f)
        //设置最大显示数量，默认9张
        ninegridview.setMaxNum(5)
        //设置图片显示间隔大小，默认3dp
        ninegridview.setSpcaeSize(4)
        //设置删除图片
        //        mNineGridView.setIcDeleteResId(R.drawable.ic_block_black_24dp);
        //设置删除图片与父视图的大小比例，默认0.25f
        //设置删除图片
        //        mNineGridView.setIcDeleteResId(R.drawable.ic_block_black_24dp);
        //设置删除图片与父视图的大小比例，默认0.25f
        ninegridview.setRatioOfDeleteIcon(0.15f)
        //设置“+”号的图片
        ninegridview.setIcAddMoreResId(R.drawable.ic_ngv_add_pic)
        //设置各类点击监听
        ninegridview.setOnItemClickListener(this)
        progressDialog = ProgressDialog(
            this@Newvehicles,
            R.style.AppTheme_Dark_Dialog
        )
        progressDialog!!.isIndeterminate = true
        progressDialog!!.setCanceledOnTouchOutside(false)
        progressDialog!!.setCancelable(true)
        token = Utils.getShared2(this, "token")
        carPlate = intent.getStringExtra("carPlate")
        dialogUtils = DialogUtils()
        confirm_button.setOnClickListener(this)
        //take_photo_lin.setOnClickListener(this)
        newvehiclesViewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application)).get(NewvehiclesViewModel::class.java)
        etPlateNumber.setText(carPlate)
//        keyboardUtil = CarKeyboardUtil(this, etPlateNumber)
//        etPlateNumber.setOnTouchListener(this)
//        etPlateNumber.addTextChangedListener(object : TextWatcher {
//            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
//
//            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
//                val text = s.toString()
//                if (s.length == 8) {
//                    rlPlateNumber.setBackgroundResource(R.drawable.btn_round_blue)
//                    imgIcon.visibility = View.VISIBLE
//                } else {
//                    rlPlateNumber.setBackgroundResource(R.drawable.btn_round_green)
//                    imgIcon.visibility = View.GONE
//                }
//                if (text.contains("港") || text.contains("澳") || text.contains("学")) {
//                    etPlateNumber.filters = arrayOf<InputFilter>(LengthFilter(7))
//                } else {
//                    etPlateNumber.filters = arrayOf<InputFilter>(LengthFilter(8))
//                }
//            }
//
//            override fun afterTextChanged(s: Editable) {
//
//            }
//        })

//        etPlateNumber.setOnFocusChangeListener { _, hasFocus ->
//            if (hasFocus) {
//                keyboardUtil!!.showKeyboard()
//                (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(this@Newvehicles.currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
//            } else {
//                keyboardUtil!!.hideKeyboard()
//                confirm_button.visibility = View.VISIBLE
//            }
//        }


        CK_1.setOnCheckedChangeListener { _, isChecked ->
            drivingLicense = if (isChecked) {
                "1"
            } else {
                "0"
            }
        }

        CK_2.setOnCheckedChangeListener { _, isChecked ->
            registration = if (isChecked) {
                "1"
            } else {
                "0"
            }
        }

        CK_3.setOnCheckedChangeListener { _, isChecked ->
            idCardCopy = if (isChecked) {
                "1"
            } else {
                "0"
            }
        }

        CK_4.setOnCheckedChangeListener { _, isChecked ->
            notice = if (isChecked) {
                "1"
            } else {
                "0"
            }
        }

        CK_5.setOnCheckedChangeListener { _, isChecked ->
            attorneyPaper = if (isChecked) {
                "1"
            } else {
                "0"
            }
        }

        CK_6.setOnCheckedChangeListener { buttonView, isChecked ->
            plateApplicationForm = if (isChecked) {
                "1"
            } else {
                "0"
            }
        }

        //标记 正常/问题
        radiogroup.setOnCheckedChangeListener { group, checkedId ->
            if (checkedId == CK_B1.id) {
                carSign = "2"
            } else if (checkedId == CK_B2.id) {
                carSign = "1"
            }
        }
        //是否保号
        mGuaranteedGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                mGuaranteedTrue.id -> guaranteed = "1"
                mGuaranteedFalse.id -> guaranteed = "0"
            }
        }
        //是否是营运车辆
        mYYGroup.setOnCheckedChangeListener { _, checkedId ->
            operating = if (checkedId == mYYTrue.id) "1" else "0"
        }
    }

    private fun Getdata() {
        newvehiclesViewModel!!.getresponsedata().observe(this, Observer { response: Response<*> ->
            if (response.status == 0) {
                progressDialog!!.dismiss()
                Toast.makeText(this, response.msg, Toast.LENGTH_LONG).show()
                finish()

            } else {
                progressDialog!!.dismiss()
                dialogUtils!!.showTwo(this@Newvehicles, "提示", response.msg)
            }
        })
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onClick(v: View?) {
        if (v == confirm_button) {
            if (TextUtils.isEmpty(etPlateNumber.text.toString())) {
                Toast.makeText(applicationContext, "车牌号不能为空", Toast.LENGTH_SHORT).show()
            } else if (etPlateNumber.text.length < 7) {
                Toast.makeText(applicationContext, "车牌号格式不对", Toast.LENGTH_SHORT).show()
            } else if (TextUtils.isEmpty(carOwner.text.toString())) {
                Toast.makeText(applicationContext, "车主姓名不能为空", Toast.LENGTH_SHORT).show()
            } else if (TextUtils.isEmpty(ownerPhone.text.toString())) {
                Toast.makeText(applicationContext, "车主电话不能为空", Toast.LENGTH_SHORT).show()
            } else if (ownerPhone.text.length < 11) {
                Toast.makeText(applicationContext, "电话号码长度不能低于11位", Toast.LENGTH_SHORT).show()
            } else if (TextUtils.isEmpty(remark.text.toString())) {
                Toast.makeText(applicationContext, "初验备注不能为空", Toast.LENGTH_SHORT).show()
            } else if (files.isEmpty()) {
                Toast.makeText(applicationContext, "车辆照片最少2张", Toast.LENGTH_SHORT).show()
            }else if (mCarSelfCodeET.text.handlerNull().isEmpty()){
                showToast("请输入车辆自编码")
            }
            else {

                progressDialog!!.setMessage("正在提交...")
                progressDialog!!.show()
                if (NetworkUtils.isConnected(applicationContext)) {
                    newvehiclesViewModel!!.AddEntranceCar(token!!, filesToMultipartBodyParts(files))
                } else {
                    Toast.makeText(applicationContext, "请检查您的网络是否连接", Toast.LENGTH_SHORT).show()
                    progressDialog!!.dismiss()
                }

            }
        }

    }

    private fun tempFile(): String? {
        val filename: String = StringUtil.get32UUID().toString() + JPG
        return StorageUtil.getWritePath(filename, StorageType.TYPE_TEMP)
    }

//    @SuppressLint("ClickableViewAccessibility")
//    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
//        if (v!!.getId() == R.id.etPlateNumber) {
//            keyboardUtil!!.hideSystemKeyBroad()
//            keyboardUtil!!.hideSoftInputMethod()
//            if (!keyboardUtil!!.isShow) keyboardUtil!!.showKeyboard()
//            confirm_button.visibility = View.INVISIBLE
//        } else {
//            if (keyboardUtil!!.isShow) keyboardUtil!!.hideKeyboard()
//            confirm_button.visibility = View.VISIBLE
//        }
//        return false
//    }
//
//    override fun onTouchEvent(event: MotionEvent?): Boolean {
//        if (keyboardUtil!!.isShow) {
//            keyboardUtil!!.hideKeyboard()
//        }
//        return super.onTouchEvent(event)
//    }


    fun filesToMultipartBodyParts(files: ArrayList<File>): ArrayList<MultipartBody.Part> {
        val parts: ArrayList<MultipartBody.Part> = ArrayList()
        for (i in files) {
            toRequestBodyOfImage("entrancePic", i)?.let { parts.add(it) }
        }
        toRequestBodyOfText("carOwner", carOwner.text.toString())?.let { parts.add(it) }
        toRequestBodyOfText("ownerPlate", etPlateNumber.text.toString())?.let { parts.add(it) }
        toRequestBodyOfText("ownerPhone", ownerPhone.text.toString())?.let { parts.add(it) }
        toRequestBodyOfText("drivingLicense", drivingLicense)?.let { parts.add(it) }
        toRequestBodyOfText("registration", registration)?.let { parts.add(it) }
        toRequestBodyOfText("idCardCopy", idCardCopy)?.let { parts.add(it) }
        toRequestBodyOfText("notice", notice)?.let { parts.add(it) }
        toRequestBodyOfText("attorneyPaper", attorneyPaper)?.let { parts.add(it) }
        toRequestBodyOfText("plateApplicationForm", plateApplicationForm)?.let { parts.add(it) }
        toRequestBodyOfText("carSign", carSign)?.let { parts.add(it) }
        toRequestBodyOfText("doesGuaranteed", guaranteed)?.let { parts.add(it) }
        toRequestBodyOfText("isOperatingCar", operating)?.let { parts.add(it) }
        toRequestBodyOfText("remark", remark.text.toString())?.let { parts.add(it) }
        //车辆自编码
        toRequestBodyOfText("selfCode", mCarSelfCodeET.text.toString())?.let { parts.add(it) }
        return parts
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_PICKER && resultCode == Activity.RESULT_OK && data != null) {
            val list: List<ImageBean> =
                data.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA)
            val resultList: MutableList<NineGridBean> =
                java.util.ArrayList()
            for (imageBean in list) {
                val nineGirdData = NineGridBean(imageBean.imagePath)
                val file = File(imageBean.imagePath)
                val newFile: File = CompressHelper.getDefault(this).compressToFile(file)
                files.add(newFile)
                resultList.add(nineGirdData)
            }
            ninegridview.addDataList(resultList)
        }
    }

    private fun toRequestBodyOfText(keyStr: String, value: String): MultipartBody.Part? {
        return MultipartBody.Part.createFormData(keyStr, value)
    }

    private fun toRequestBodyOfImage(keyStr: String, pFile: File): MultipartBody.Part? {
        val requestBody =
            RequestBody.create(MediaType.parse("multipart/form-data"), pFile)
        return MultipartBody.Part.createFormData(keyStr, pFile.name, requestBody)
    }

    override fun onNineGirdItemDeleted(position: Int, gridBean: NineGridBean?, imageContainer: NineGirdImageContainer?) {
        if (files.isEmpty()) {
            files.removeAt(position)
        }
    }

    override fun onNineGirdItemClick(position: Int, gridBean: NineGridBean?, imageContainer: NineGirdImageContainer?) {

    }

    override fun onNineGirdAddMoreClick(cha: Int) {
        //编辑模式下，图片展示数量尚未达到最大数量时，会显示一个“+”号，点击后回调这里
        val imageLoader = ImagePicker()
            .cachePath(Environment.getExternalStorageDirectory().absolutePath)
            .pickType(ImagePickType.MULTI)
            .displayer(ImagePickerLoader())
            .maxNum(cha)
            .start(this, REQUEST_CODE_PICKER)
    }
}